package com.hst.web.base.proxy;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.meta.MetaData;
import com.hst.core.meta.proxies.DefaultDataProxy;
import com.hst.web.auth.po.User;
import com.hst.web.base.entity.TInvitationCode;
import com.hst.web.base.ui.InvitationCodeGen;
import com.hst.web.common.utils.InvitationCodeUtil;

public class InvitationCodeGenProxy extends DefaultDataProxy {

	@Autowired
	IORDao dao;

	@Override
	public Object save(MetaData data) throws Exception {
		User user = (User) ServiceContext.getInstance().getUser();
		InvitationCodeGen invitationCodeGen = (InvitationCodeGen) data;
		
		String invitationCode;
		TInvitationCode tInvitationCode;
		List<TInvitationCode> invitationCodeList = new ArrayList<>();
		
		Integer invitationCodeCount = invitationCodeGen.getInvitationCodeCount();
		for (int i = 0; i < invitationCodeCount; i++) {
			invitationCode = InvitationCodeUtil.genInvitationCode();
			tInvitationCode = dao.get(TInvitationCode.class, invitationCode);
			while (tInvitationCode != null) {
				invitationCode = InvitationCodeUtil.genInvitationCode();
				tInvitationCode = dao.get(TInvitationCode.class, invitationCode);
			}
			
			tInvitationCode = new TInvitationCode();
			tInvitationCode.setInvitationCode(invitationCode);
			tInvitationCode.setOpCreate(user.getId());
			dao.save(tInvitationCode);
			invitationCodeList.add(tInvitationCode);
		}
		return invitationCodeList;
	}

}
